// https://leetcode.cn/problems/surrounded-regions/description/

// 算法思路总结：
// 1. 从边界上的'O'开始BFS标记所有相连的'O'
// 2. 边界相连的'O'是不被围绕的区域，标记后保留
// 3. 遍历整个网格，将未被标记的'O'改为'X'
// 4. 使用方向数组进行四方向扩展，vis数组记录访问状态
// 5. 时间复杂度：O(m×n)，空间复杂度：O(m×n)

#include <iostream>
using namespace std;

#include <queue>
#include <vector>
#include <cstring>
#include <algorithm>

class Solution 
{
public:
    typedef pair<int, int> PII;
    bool vis[201][201];
    int m, n;
    int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
    void solve(vector<vector<char>>& board) 
    {
        m = board.size(), n = board[0].size();
        memset(vis, 0, sizeof(vis));

        for (int i = 0 ; i < m ; i++)
        {
            for (int j = 0 ; j < n ; j++)
            {
                if (i == 0 || i == m - 1 || j == 0 || j == n - 1)
                {
                    if (vis[i][j] == false && board[i][j] == 'O')
                    {
                        bfs(i, j, board);
                    }
                }
            }
        }

        for (int i = 0 ; i < m ; i++)
        {
            for (int j = 0 ; j < n ; j++)
            {
                if (board[i][j] == 'O' && vis[i][j] == false)
                {
                    board[i][j] = 'X';
                }
            }
        }
    }

    void bfs(int i, int j, vector<vector<char>>& board)
    {
        queue<PII> q;
        q.push({i, j});
        vis[i][j] = true;

        while (!q.empty())
        {
            auto [a, b] = q.front();
            q.pop();

            for (int i = 0 ; i < 4 ; i++)
            {
                int x = a + dx[i], y = b + dy[i];
                if (x >= 0 && y >= 0 && x < m && y < n && vis[x][y] == false && board[x][y] == 'O')
                {
                    q.push({x, y});
                    vis[x][y] = true;
                }
            }
        }
    }

    void printBoard(vector<vector<char>>& board)
    {
        cout << "[";
        for (int i = 0; i < board.size(); i++) 
        {
            cout << "[";
            for (int j = 0; j < board[i].size(); j++) 
            {
                cout << "'" << board[i][j] << "'";
                if (j < board[i].size() - 1) 
                    cout << ",";
            }
            cout << "]";
            if (i < board.size() - 1) 
                cout << ",";
        }
        cout << "]" << endl;
    }
};

int main()
{
    vector<vector<char>> board1 = {
        {'X','X','X','X'},
        {'X','O','O','X'},
        {'X','X','O','X'},
        {'X','O','X','X'}
    };

    vector<vector<char>> board2 = {
        {'X'}
    };

    Solution sol;
    sol.solve(board1);
    sol.solve(board2);

    sol.printBoard(board1);
    sol.printBoard(board2);

    return 0;
}